﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Ricciolo.StylesExplorer.Model;
using System.ComponentModel;
using System.Xml.XPath;
using System.Xml.Serialization;
using Ricciolo.StylesExplorer.MarkupReflection;
using System.Xml;
using Ricciolo.StylesExplorer.Components;
using System.IO;

namespace Ricciolo.StylesExplorer.Controls
{
    class XamlDataTreeNode : ExplorerTreeNode, ITreeNodeChildren, IFullXPathNavigable
    {

        private IXamlData xamlData;

        public XamlDataTreeNode(IXamlData xamlData)
        {
            this.xamlData = xamlData;
            XPathNavigator navigator = xamlData.CreateNavigator();

            // Recupero la lista di risorse
            XmlNamespaceManager nsManager = new XmlNamespaceManager(navigator.NameTable);
            nsManager.AddNamespace("p", XmlPIMapping.PresentationNamespace);
            nsManager.AddNamespace("x", XmlPIMapping.XamlNamespace);

            navigator = navigator.SelectSingleNode("@x:Key", nsManager);
            if (navigator != null)
                this.Text = String.Format("{0}: {1}", xamlData.Name, navigator.Value);
            else
                this.Text = xamlData.Name;

            this.ImageKey = "Xaml";
            this.SelectedImageKey = this.ImageKey;
        }

        #region ITreeNodeChildren Members

        System.ComponentModel.IBindingList ITreeNodeChildren.Children
        {
            get { return xamlData.Dependencies as IBindingList; }
        }

        #endregion

        #region IFullXPathNavigable Members

        XPathNavigator IFullXPathNavigable.CreateNavigator(bool includeDependencies)
        {
            if (xamlData is IXPathNavigable)
            {
                if (includeDependencies && xamlData.Dependencies.Count > 0)
                {
                    using (StringWriter writer = new StringWriter())
                    {
                        using (XmlTextWriter xmlWriter = new XmlTextWriter(writer))
                        {
                            xmlWriter.WriteStartElement("ResourceDictionary", XmlPIMapping.PresentationNamespace);
                            DumpData(xmlWriter, xamlData);
                            xmlWriter.WriteEndElement();
                        }

                        return new XPathDocument(new StringReader(writer.ToString())).CreateNavigator();
                    }
                }
                else
                    return xamlData.CreateNavigator();
            }

            return null;
        }

        private void DumpData(XmlTextWriter xmlWriter, IXamlData xamlData)
        {
            foreach (IXamlData xd in xamlData.Dependencies)
            {
                DumpData(xmlWriter, xd);
            }
            xmlWriter.WriteNode(xamlData.CreateNavigator(), false);
        }

        #endregion
    }
}
